﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using Lucene.Net;
using Lucene.Net.Index;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Highlight;
using System.Text;
using OgilvyOne.BLL;

public partial class allergy_search_search : System.Web.UI.Page
{
    //总记录数目
    protected int TotalCountRecord;
    //每页显示的条数
    protected int PageItem = 10;
    protected string strUrl = string.Empty;
    //当前页数
    protected int CurrentPage = 1;
    protected string kes;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["page"] != null)
        {
            if (!Int32.TryParse(Request.QueryString["page"].ToString(), out CurrentPage))
            {
                Response.Write("请输入数字分页参数。");
                Response.End();
                return;
            }
        }
        if (!this.IsPostBack)
        {
            try
            {
                if (Request.Params["key"] != null)
                {
                    kes = Server.UrlDecode(Request.Params["key"]);
                    if (BLLArticleInfo.selkey(kes) == 1)
                    {
                        int number;
                        DataTable dt = BLLArticleInfo.getKeywords(kes);
                        foreach (DataRow row in dt.Rows)
                        {
                            number = Convert.ToInt32(row["num"].ToString()) + 1;
                            BLLArticleInfo.updatekey(number.ToString(), kes);
                        }
                    }
                    else
                    {
                        BLLArticleInfo.inskey(kes);
                    }
                }
                this.BindData();

            }
            catch (Exception)
            { }

        }
    }
    public void BindData()
    {
        if (Request.Params["key"] != null)
        {
            string key = Server.UrlDecode(Request.Params["key"]);
            strUrl = string.Format("&key={0}", key);
            if (key != string.Empty)
            {
                this.Rep_Resource.DataSource = GetTable(key, PageItem, CurrentPage, out TotalCountRecord);
                this.Rep_Resource.DataBind();
                BuildPagers();
                this.Pan_Page.Visible = true;

            }
            else
            {
                this.Pan_Page.Visible = false;
            }
        }
    }
    public DataTable GetTable(string key, Int32 pageSize, Int32 pageIndex, out int Total)
    {
            DataRow myrow;
            DataTable mytab = new DataTable();
            mytab.Columns.Add("ARTICLEID");
            mytab.Columns.Add("TITLE");
            mytab.Columns.Add("SUMMARY");
            mytab.Columns.Add("ADD_TIME");
            mytab.Columns.Add("parentename");
            mytab.Columns.Add("childenamel");
            mytab.Columns.Add("STATICPAGENAME");
            mytab.Clear();
            IndexReader reader = IndexReader.Open(Server.MapPath("reader/"));
            IndexSearcher searcher = new IndexSearcher(reader);
            Lucene.Net.Analysis.Analyzer analyzer = new StandardAnalyzer();
            string query = this.Txt_Key.Text.Trim();
            Lucene.Net.Analysis.Analyzer highanalyzer = new StandardAnalyzer();
            MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[] { "TITLE", "SUMMARY" }, highanalyzer);
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>"); // 这是定义了在页面如何通过css来控制关键字的特征
            Query highquery = parser.Parse(key);

            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(highquery));

            //Sort sort = new Sort(new SortField("id",SortField.FIELD_SCORE));
            Hits myhit = searcher.Search(highquery);
            highlighter.SetTextFragmenter(new SimpleFragmenter(100));


            Total = myhit.Length();
            for (int i = ((pageIndex - 1) * pageSize); i < (pageIndex * pageSize); i++)
            {
                if (i == Total)
                {
                    break;
                }
                else
                {
                    Lucene.Net.Documents.Document doc = myhit.Doc(i);
                    string s_Title = doc.Get("TITLE");
                    string s_Content = doc.Get("SUMMARY");
                    Lucene.Net.Analysis.TokenStream TitlekenStream = highanalyzer.TokenStream("TITLE", new System.IO.StringReader(s_Title));
                    Lucene.Net.Analysis.TokenStream ContentkeStream = highanalyzer.TokenStream("SUMMARY", new System.IO.StringReader(s_Content));
                    string Title = highlighter.GetBestFragments(TitlekenStream, s_Title, 2, "...");
                    string Content = highlighter.GetBestFragments(ContentkeStream, s_Content, 0, "..");

                    myrow = mytab.NewRow();
                    myrow[0] = doc.Get("ARTICLEID").ToString();
                    myrow[1] = Title;
                    myrow[2] = Content;
                    myrow[3] = doc.Get("ADD_TIME").ToString();
                    myrow[4] = doc.Get("parentename").ToString();
                    myrow[5] = doc.Get("childenamel").ToString();
                    myrow[6] = doc.Get("STATICPAGENAME").ToString();
                    mytab.Rows.Add(myrow);
                    searcher.Close();
                    myrow.AcceptChanges();
                }

            }
            return mytab; 
    }

    //public void CreateIndex(string path)
    //{
    //    SqlDataReader Dr = GetDR();
    //    IndexWriter writer = new IndexWriter(Server.MapPath(path), new ChineseAnalyzer(), true);
    //    writer.SetMergeFactor(20);  //      调整segment合并的频率和大小
    //    while (Dr.Read())
    //    {

    //        Document doc = GetDocumentObj(Dr["ARTICLEID"].ToString(), Dr["TITLE"].ToString(), Dr["SUMMARY"].ToString(), Dr["ADD_TIME"].ToString());
    //        //    doc.SetBoost(1.5);
    //        //写入索引文档
    //        writer.AddDocument(doc);

    //    }
    //    Dr.Close();
    //    //优化文档
    //    writer.Optimize();
    //    //关闭
    //    writer.Close();
    //}
    //public SqlDataReader GetDR()
    //{
    //    SqlConnection Conn = new SqlConnection("server=10.172.12.42;uid=nestle_allergy;password=nestle_allergy;database=nestle_allergy;min pool size=4;min pool size=4;max pool size=100;packet size=3072");
    //    //SqlConnection Conn = new SqlConnection("server=HUNTER\\HUNTER05;uid=sa;password=123@qwe;database=nestle;min pool size=4;min pool size=4;max pool size=100;packet size=3072");
    //    SqlCommand Cmd = new SqlCommand();
    //    Cmd.Connection = Conn;
    //    Conn.Open();
    //    Cmd.CommandText = string.Format("select  * from CMS_ARTICLE");
    //    SqlDataReader Dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
    //    return Dr;

    //}
    //public Document GetDocumentObj(string articleId, string Title, string Content, string Add_Time)
    //{
    //    Document doc = new Document();
    //    doc.Add(new Field("ARTICLEID", articleId, Field.Store.YES, Field.Index.UN_TOKENIZED));
    //    doc.Add(new Field("TITLE", Title, Field.Store.YES, Field.Index.TOKENIZED));
    //    doc.Add(new Field("SUMMARY", Content, Field.Store.YES, Field.Index.TOKENIZED));
    //    doc.Add(new Field("ADD_TIME", Add_Time, Field.Store.YES, Field.Index.UN_TOKENIZED));
    //    return doc;
    //}
    public void BuildPagers()
    {
        //偏移量
        int Step = 10;
        int LeftNum = 0;
        int RightNum = 0;
        string PageUrl = Request.FilePath;
        int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
        if (CurrentPage - Step < 1)
        {
            LeftNum = 1;
        }
        else
        {
            LeftNum = CurrentPage - Step;
        }

        if (CurrentPage + Step > PageCount)
        {
            RightNum = PageCount;
        }
        else
        {
            RightNum = CurrentPage + Step;
        }
        StringBuilder OutPut = new StringBuilder();
        OutPut.Append("<li id='page_yema' style='float:left;' >");
        for (int i = LeftNum; i <= RightNum; i++)
        {
            if (i == CurrentPage)
            {
                OutPut.Append("<font style='margin-left:30px;' color=red>");
                OutPut.Append(i.ToString());
                OutPut.Append("</font>");
            }
            else
            {
                OutPut.Append("<a style='margin-left:30px;margin-top:10px' href='");
                OutPut.Append(PageUrl);
                OutPut.Append("?page=");
                OutPut.Append(i.ToString());
                OutPut.Append(strUrl);
                OutPut.Append("'>");
                OutPut.Append(i.ToString());
                OutPut.Append("</a>");
            }
        }
        OutPut.Append("</li>");
        if (CurrentPage > 1)
        {
            OutPut.Insert(0, string.Format("<li style='float:left;padding-left:10px'><a href='{0}?page={1}{2}'>上一页</a></li>", PageUrl, (CurrentPage - 1), strUrl));

            OutPut.Insert(0, string.Format("<li style='float:left'><a href='{0}?page={1}{2}'><img src='/allergy/images/4-t5.png' alt='上一页' width='22px' height='22px' border='0' /></a></li>", PageUrl, (CurrentPage - 1), strUrl));
        }

        if (CurrentPage < PageCount)
        {
            OutPut.Append("<li style='float:left;padding-left:30px'><a href='");
            OutPut.Append(PageUrl);
            OutPut.Append("?page=");
            OutPut.Append(CurrentPage + 1);
            OutPut.Append(strUrl);
            OutPut.Append("'>下一页</a></li>");

            OutPut.Append("<li style='float:left'><a href='");
            OutPut.Append(PageUrl);
            OutPut.Append("?page=");
            OutPut.Append(CurrentPage + 1);
            OutPut.Append(strUrl);
            OutPut.Append("'><img src='/allergy/images/4-t6.png' alt='下一页' width='22px' height='22px' border='0' style='padding-left:10px; float:left;' /></a></li>");
        }
        //OutPut.Append("<li id='page_yema' style='float:left; padding-top:6px;'>");
        //for (int i = LeftNum; i <= RightNum; i++)
        //{
        //    if (i == CurrentPage)
        //    {
        //        OutPut.Append("<font style='margin-left:3px;' color=red>");
        //        OutPut.Append(i.ToString());
        //        OutPut.Append("</font>");
        //    }
        //    else
        //    {
        //        OutPut.Append("<a style='margin-left:3px;' href='");
        //        OutPut.Append(PageUrl);
        //        OutPut.Append("?page=");
        //        OutPut.Append(i.ToString());
        //        OutPut.Append(strUrl);
        //        OutPut.Append("'>");
        //        OutPut.Append(i.ToString());
        //        OutPut.Append("</a>");
        //    }
        //}
        //OutPut.Append("</li>");
        //if (CurrentPage > 1)
        //{
        //    OutPut.Insert(0, string.Format("<li style='float:left'><a href='{0}?page={1}{2}'><img src='/allergy/images/4-t5.png' alt='上一页' width='22px' height='22px' border='0' style='margin-top:3px;'/></a></li>", PageUrl, (CurrentPage - 1), strUrl));
        //}

        //if (CurrentPage < PageCount)
        //{
        //    OutPut.Append("<li style='float:left'><a href='");
        //    OutPut.Append(PageUrl);
        //    OutPut.Append("?page=");
        //    OutPut.Append(CurrentPage + 1);
        //    OutPut.Append(strUrl);
        //    OutPut.Append("'><img src='/allergy/images/4-t6.png' alt='下一页' width='22px' height='22px' border='0' style='margin-top:3px;' /></a></li>");
        //}
        this.PageInfo.Text = OutPut.ToString();
        //this.left.Text = string.Format("总记录数:<font color='red'>{0}</font>  总页数:<font color='red'>{1}</font>", TotalCountRecord, PageCount);
    }

    protected void Btn_Search_Click(object sender, CommandEventArgs e)
    {
        string key = this.Txt_Key.Text.Trim();
        if (key != null && key != "")
        {
            Response.Redirect(string.Format("search.aspx?key={0}", key));
        }

    }
}
